import React, { useEffect } from 'react'
import * as echarts from 'echarts'
import { Card } from 'antd'
import barOption from '@/plugins/barOption'
import pieOption from '@/plugins/pieOption'
import { reqOrderStateCount } from '@/api/order'

const boxStye: React.CSSProperties = {
  width: '100%',
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'center',
  marginTop: '10px'
}

const barStyle: React.CSSProperties = {
  height: '300px',
  width: '50%',
  marginRight: '10px',
  padding: '10px'
}

const pieStyle: React.CSSProperties = {
  height: '300px',
  width: '50%',
  padding: '10px'
}

// 定义一个接口来明确 item 的类型
interface OrderItem {
  orderState: unknown
  count: unknown
}
const Index: React.FC = () => {
  let barMyChart: echarts.ECharts | null = null
  let pieMyChart: echarts.ECharts | null = null
  
  useEffect(() => {
    initBarChart()
    
    // 获取订单数据
    const getOrderMessage = async () => {
      try {
        const res = await reqOrderStateCount()

        const nameArr: unknown[] = res.data.map(
          (item: OrderItem) => item.orderState
        )
        const valueArr: unknown = res.data.map((item: OrderItem) => item.count)
        const legendArr: unknown = []
        res.data.forEach((item: OrderItem) => {
          legendArr?.push({
            value: item.count,
            name: item.orderState
          })
        })
        barMyChart?.setOption({
          xAxis: {
            data: nameArr
          },
          series: [
            {
              data: valueArr
            }
          ]
        })

        pieMyChart?.setOption({
          series: [{ data: legendArr }]
        })
      } catch (error) {
        console.error('获取订单数据失败:', error)
      }
    }
    
    getOrderMessage()
  }, [])

  const initBarChart = () => {
    const barChartDom = document.getElementById('bar')
    barMyChart = echarts.init(barChartDom)
    const pieChartDom = document.getElementById('pie')
    pieMyChart = echarts.init(pieChartDom)
    const barOptions = barOption
    const pieOptions = pieOption
    // eslint-disable-next-line @typescript-eslint/no-unused-expressions
    barOptions && barMyChart.setOption(barOptions)
    // eslint-disable-next-line @typescript-eslint/no-unused-expressions
    barOptions && pieMyChart.setOption(pieOptions)
    window.addEventListener('resize', () => {
      barMyChart?.resize()
      pieMyChart?.resize()
    })
  }
  
  return (
    <div style={boxStye}>
      <Card className="bar" id="bar" style={barStyle}></Card>
      <Card className="pie" id="pie" style={pieStyle}></Card>
    </div>
  )
}

export default Index
